<template>
	<div>
		<el-card class="!border-none" shadow="never">
			<el-page-header :content="$route.meta.title" @back="$router.back()" />
		</el-card>
		<el-card class="mt-4 !border-none" shadow="never">
			<div class="font-medium mb-7">基础信息</div>
			<el-form v-if="choose_type == 0" ref="formRef" class="ls-form" :model="formData" :rules="rules" label-width="120px">
				<el-form-item v-if="!route.query.id" label="群聊类型">
					<div class="w-80">
						<el-radio-group v-model="choose_type">
							<el-radio :label="0">其他群聊</el-radio>
							<el-radio :label="1">对单群聊</el-radio>
							<el-radio :label="5">话题群聊</el-radio>
						</el-radio-group>
					</div>
				</el-form-item>
                <el-form-item label="群名称" prop="name">
					<div class="w-80">
						<el-input
							v-model="formData.name"
							placeholder="请输入群名称"
							type="text"
							maxlength="30"
							show-word-limit
							clearable
						/>
					</div>
				</el-form-item>
				<el-form-item label="群图像" prop="pics">
					<div class="w-80">
						<div>
							<material-picker v-model="formData.pics" :limit="1"/>
						</div>
						<div class="form-tips">建议尺寸：200*200px</div>
					</div>
				</el-form-item>
				<el-form-item label="简介" prop="introduction">
					<div class="w-80">
						<el-input
							v-model="formData.introduction"
							placeholder="请输入简介"
							type="textarea"
                  			:autosize="{ minRows: 2, maxRows: 12}"
							maxlength="600"
							show-word-limit
							clearable
						/>
					</div>
				</el-form-item>
				<el-form-item label="公告" prop="notification">
					<div class="w-80">
						<el-input
							v-model="formData.notification"
							placeholder="请输入公告"
							type="textarea"
                  			:autosize="{ minRows: 2, maxRows: 12}"
							maxlength="600"
							show-word-limit
							clearable
						/>
					</div>
				</el-form-item>
				<el-form-item label="管理员" prop="userinfo.realname">
					<div class="w-80">
						<el-input
							v-model="formData.userinfo.realname"
							placeholder="请选择管理员"
							type="text"
							maxlength="30"
							show-word-limit
							clearable
							readonly
						>
							<template #append>
								<el-button @click="addUser" :disabled="!!route.query.id">
									添加
									<icon name="el-icon-Plus"/>
								</el-button>
							</template>
						</el-input>
					</div>
				</el-form-item>
				<el-form-item label="添加好友">
					<div class="w-80">
						<el-radio-group v-model="formData.can_add_friend">
							<el-radio :label="1">是</el-radio>
							<el-radio :label="0">否</el-radio>
						</el-radio-group>
					</div>
				</el-form-item>
				<el-form-item v-if="formData.group_type == 5" label="最大人数" prop="max_user">
					<div class="w-80">
						<el-input
							v-model="formData.max_user"
							placeholder="请输入最大人数"
							type="number"
							maxlength="30"
							show-word-limit
							clearable
						/>
					</div>
				</el-form-item>
				<el-form-item v-if="formData.group_type == 5" label="群聊开始时间" prop="start_time">
					<div class="w-80">
						<el-date-picker
                            v-model="formData.start_time"
                            type="datetime"
                            format="YYYY-MM-DD HH:mm"
							date-format="MMM DD, YYYY"
							time-format="HH:mm"
                            value-format="X"
                            placeholder="请选择日期"
                        />
					</div>
				</el-form-item>
				<el-form-item v-if="formData.group_type == 5" label="群聊结束时间" prop="end_time">
					<div class="w-80">
						<el-date-picker
                            v-model="formData.end_time"
                            type="datetime"
                            format="YYYY-MM-DD HH:mm"
							date-format="MMM DD, YYYY"
							time-format="HH:mm"
                            value-format="X"
                            placeholder="请选择日期"
                        />
					</div>
				</el-form-item>
			</el-form>
			<el-form v-if="choose_type == 1" ref="orderRef" class="ls-form" :model="orderData" :rules="orderRules" label-width="120px">
				<!-- 对单群聊 -->
				 <el-form-item v-if="!route.query.id" label="群聊类型">
					<div class="w-80">
						<el-radio-group v-model="choose_type">
							<el-radio :label="0">其他群聊</el-radio>
							<el-radio :label="1">对单群聊</el-radio>
							<el-radio :label="5">话题群聊</el-radio>
						</el-radio-group>
					</div>
				</el-form-item>
				<el-form-item label="管家账号" prop="userinfo.gjname">
					<div class="w-80">
						<el-input
							v-model="orderData.userinfo.gjname"
							placeholder="请选择管家"
							type="text"
							maxlength="30"
							show-word-limit
							clearable
							readonly
						>
							<template #append>
								<el-button @click="addGj">
									添加
									<icon name="el-icon-Plus"/>
								</el-button>
							</template>
						</el-input>
					</div>
				</el-form-item>
				<el-form-item label="用户账号" prop="userinfo.username">
					<div class="w-80">
						<el-input
							v-model="orderData.userinfo.username"
							placeholder="请选择用户"
							type="text"
							maxlength="30"
							show-word-limit
							clearable
							readonly
						>
							<template #append>
								<el-button @click="newAddUser(0)">
									添加
									<icon name="el-icon-Plus"/>
								</el-button>
							</template>
						</el-input>
					</div>
				</el-form-item>
				<el-form-item label="渠道账号" prop="userinfo.channelname">
					<div class="w-80">
						<el-input
							v-model="orderData.userinfo.channelname"
							placeholder="请选择渠道"
							type="text"
							maxlength="30"
							show-word-limit
							clearable
							readonly
						>
							<template #append>
								<el-button @click="newAddUser(1)">
									添加
									<icon name="el-icon-Plus"/>
								</el-button>
							</template>
						</el-input>
					</div>
				</el-form-item>
				<el-form-item  label="群图像" prop="pics">
					<div class="w-80">
						<div>
							<material-picker v-model="orderData.pics" :limit="1"/>
						</div>
						<div class="form-tips">建议尺寸：200*200px</div>
					</div>
				</el-form-item>
			</el-form>
			<!-- 话题群聊 -->
			<el-form v-if="choose_type == 5" ref="huaRef" class="ls-form" :model="huaData" :rules="rules" label-width="120px">
				<el-form-item v-if="!route.query.id" label="群聊类型">
					<div class="w-80">
						<el-radio-group v-model="choose_type">
							<el-radio :label="0">其他群聊</el-radio>
							<el-radio :label="1">对单群聊</el-radio>
							<el-radio :label="5">话题群聊</el-radio>
						</el-radio-group>
					</div>
				</el-form-item>
                <el-form-item label="群名称" prop="name">
					<div class="w-80">
						<el-input
							v-model="huaData.name"
							placeholder="请输入群名称"
							type="text"
							maxlength="30"
							show-word-limit
							clearable
						/>
					</div>
				</el-form-item>
				<el-form-item label="群图像" prop="pics">
					<div class="w-80">
						<div>
							<material-picker v-model="huaData.pics" :limit="1"/>
						</div>
						<div class="form-tips">建议尺寸：200*200px</div>
					</div>
				</el-form-item>
				<el-form-item label="简介" prop="introduction">
					<div class="w-80">
						<el-input
							v-model="huaData.introduction"
							placeholder="请输入简介"
							type="textarea"
                  			:autosize="{ minRows: 2, maxRows: 12}"
							maxlength="600"
							show-word-limit
							clearable
						/>
					</div>
				</el-form-item>
				<el-form-item label="公告" prop="notification">
					<div class="w-80">
						<el-input
							v-model="huaData.notification"
							placeholder="请输入公告"
							type="textarea"
                  			:autosize="{ minRows: 2, maxRows: 12}"
							maxlength="600"
							show-word-limit
							clearable
						/>
					</div>
				</el-form-item>
				<el-form-item label="管理员" prop="userinfo.realname">
					<div class="w-80">
						<el-input
							v-model="huaData.userinfo.realname"
							placeholder="请选择管理员"
							type="text"
							maxlength="30"
							show-word-limit
							clearable
							readonly
						>
							<template #append>
								<el-button @click="addUser" :disabled="!!route.query.id">
									添加
									<icon name="el-icon-Plus"/>
								</el-button>
							</template>
						</el-input>
					</div>
				</el-form-item>
				<el-form-item label="添加好友">
					<div class="w-80">
						<el-radio-group v-model="huaData.can_add_friend">
							<el-radio :label="1">是</el-radio>
							<el-radio :label="0">否</el-radio>
						</el-radio-group>
					</div>
				</el-form-item>
				<el-form-item label="最大人数" prop="max_user">
					<div class="w-80">
						<el-input
							v-model="huaData.max_user"
							placeholder="请输入最大人数"
							type="number"
							maxlength="30"
							show-word-limit
							clearable
							max="1000"
						/>
					</div>
				</el-form-item>
				<el-form-item label="群聊开始时间" prop="start_time">
					<div class="w-80">
						<el-date-picker
                            v-model="huaData.start_time"
                            type="datetime"
                            format="YYYY-MM-DD HH:mm"
							date-format="MMM DD, YYYY"
							time-format="HH:mm"
                            value-format="X"
                            placeholder="请选择日期"
                        />
					</div>
				</el-form-item>
				<el-form-item label="群聊结束时间" prop="end_time">
					<div class="w-80">
						<el-date-picker
                            v-model="huaData.end_time"
                            type="datetime"
                            format="YYYY-MM-DD HH:mm"
							date-format="MMM DD, YYYY"
							time-format="HH:mm"
                            value-format="X"
                            placeholder="请选择日期"
                        />
					</div>
				</el-form-item>
			</el-form>
		</el-card>
		<el-card v-if="route.query.id" class="mt-4 !border-none" header="群聊成员" shadow="never">
			<el-button type="primary" class="mb-4" @click="onAdd">
                <template #icon>
                    <icon name="el-icon-Plus"/>
                </template>
				添加成员
            </el-button>
			<el-table size="large" v-loading="pager.loading" :data="pager.lists">
				<el-table-column type="index" label="序号" min-width="80" :index="indexAdd"/>
				<el-table-column label="名称" min-width="130" prop="realname"/>
				<el-table-column label="图片" min-width="100" prop="attach_urls">
                    <template #default="{ row }">
                        <div class="flex align-middle">
                            <el-image style="width: 38px; height: 38px"
								:src="row.face"
								:zoom-rate="1.2"
								:max-scale="7"
								:min-scale="0.2" 
								fit="contain"
								:preview-teleported="true"
								:preview-src-list="[row.face]">
							</el-image>
                        </div>
                    </template>
                </el-table-column>
				<el-table-column label="账号" min-width="130" prop="account"/>
				<el-table-column label="操作" min-width="130">
					<template #default="{ row }">
						<el-button size="small" v-perms="['user.group/delUser']" type="danger" @click="onDel(row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
			<div class="flex justify-end mt-4">
                <pagination v-model="pager" @change="getLists" />
            </div>
		</el-card>
        <check_demand ref="checkDemand" @backAdmin="backAdmin" @backClose="backClose"></check_demand>
		<new_demand ref="newDemand" :out_type="0" @backAdmin="newBackAdmin"></new_demand>
		<new_demand ref="channelDemand" :out_type="1" @backAdmin="newBackAdmin"></new_demand>
		<!-- <new_demand ref="gjDemand" :out_type="2" @backAdmin="newBackAdmin"></new_demand> -->
		<add_guanjia ref="addGuanjia" @backGj="backGj"></add_guanjia>
		<footer-btns>
			<el-button type="primary" v-perms="['user.group/saveGroup']" @click="handleSave" v-prevent-reclick="3000">保存</el-button>
		</footer-btns>
	</div>
</template>

<script lang="ts" setup name="demandReviewDetail">
	import type { FormInstance } from 'element-plus'
	import { groupInfo, groupUser, saveGroup, delUser, createCooperationGroup } from '@/api/group';
	import check_demand from './check_demand.vue'
	import new_demand from '../../cooperate/lists/check_demand.vue'
	import add_guanjia from './add_guanjia.vue';
	import { usePaging } from '@/hooks/usePaging';
	import feedback from '@/utils/feedback'
	const route = useRoute()
	const router = useRouter()
	const choose_type = ref(0)
	const formData:any = reactive({
		id: '',
		name: '',
		pics: '',
		introduction: '',
		notification: '',
		userinfo: {
			realname: ''
		},
		user_id: '',
		user_type: '',
		can_add_friend: 1,
		start_time: '',
		end_time: '',
		max_user: 0,
		group_type: 0
	})
	const orderData:any = reactive({
		user_id: '',
		channel_id: '',
		pics: '',
		butler_user_id: '',
		userinfo: {
			gjname: '',
			username: '',
			channelname: ''
		},
		user_type: ''
	})
	const huaData:any = reactive({
		id: '',
		name: '',
		pics: '',
		introduction: '',
		notification: '',
		userinfo: {
			realname: ''
		},
		user_id: '',
		user_type: '',
		can_add_friend: 1,
		start_time: '',
		end_time: '',
		max_user: ''
	})
	const validateTime = (rule:any, value:any, callback:any) => {
		if (!value) {
			callback(new Error('请选择开始时间'));
		} else if (huaData.start_time > huaData.end_time) {
			callback(new Error('开始时间不能大于结束时间'));
		} else {
			callback();
		}
	}
	const validateUser = (rule:any, value:any, callback:any) => {
		if (!value) {
			callback(new Error('请填写最大人数'));
		} else if (value > 1000) {
			callback(new Error('群人数最大1000'));
		} else {
			callback();
		}
	}
	const rules = reactive({
		name: [{required: true, message: '请填写群名称', trigger: 'blur'}],
		pics: [{required: true, message: '请选择群图像', trigger: 'blur'}],
		introduction: [{required: true, message: '请填写简介', trigger: 'blur'}],
		notification: [{required: true, message: '请填写公告', trigger: 'blur'}],
		'userinfo.realname': [{required: true, message: '请选择管理员', trigger: 'blur'}],
		start_time: [{required: true, validator: validateTime, trigger: 'blur'}],
		end_time: [{required: true, message: '请选择结束时间', trigger: 'blur'}],
		max_user: [{required: true, validator: validateUser, trigger: 'blur'}],
	})
	const orderRules = reactive({
		'userinfo.gjname': [{required: true, message: '请选择管家', trigger: 'blur'}],
		'userinfo.username': [{required: true, message: '请选择用户', trigger: 'blur'}],
		'userinfo.channelname': [{required: true, message: '请选择渠道', trigger: 'blur'}],
		pics: [{required: true, message: '请选择群图像', trigger: 'blur'}],
	})
	const checkDemand = ref()
	const addUser = (value : any) => {
		checkDemand.value.init();
	}
	
	const newDemand = ref()
	const channelDemand = ref()
	const addGuanjia = ref()
	const addGj = () => {
		addGuanjia.value.init();
	}
	const newAddUser = (num : any) => {
		if (num == 0) {
			newDemand.value.init(num);
		} else if (num == 1) {
			channelDemand.value.init(num);
		}
	}
	
	
	const formRef = shallowRef<FormInstance>()
	const orderRef = shallowRef<FormInstance>()
	const huaRef = shallowRef<FormInstance>()

	const getDetails = async () => {
		const data = await groupInfo({
			group_id: route.query.id
		})
		Object.keys(formData).forEach((key) => {
			formData[key] = data.info[key]
		})
	}
	// 选择管理员返回
	const backAdmin = (row: any)=> {
		console.log('backAdmin')
		console.log(row)
		if (choose_type.value == 0) {
			formData.userinfo.realname = row.real_name;
			formData.user_id = row.user_id;
			formData.user_type = row.user_type;
			formRef.value?.clearValidate();
		} else {
			huaData.userinfo.realname = row.real_name;
			huaData.user_id = row.user_id;
			huaData.user_type = row.user_type;
			huaRef.value?.clearValidate();
		}
		
	}
	const backGj = (row:any) => {
		console.log(row)
		orderData.userinfo.gjname = row.real_name;
		orderData.butler_user_id = row.user_id;
	}
	const newBackAdmin = (row: any, type: number) => {
		console.log(row)
		console.log(type)
		if (type == 0) {
			orderData.userinfo.username = row.real_name;
			orderData.user_id = row.user_id;
			orderData.user_type = row.user_type;
		} else {
			orderData.userinfo.channelname = row.real_name;
			orderData.channel_id = row.id;
		}
	}
	const backClose = () => {
		route.query.id && getLists();
	}

	// 切页序号变化
    const indexAdd = (index: number) => {
        const page = pager.page // 当前页码
        const pagesize = pager.size // 每页条数
        return index + 1 + (page - 1) * pagesize
    }
	let queryParams:any = reactive({
		group_id: route.query.id
        
	});
	const { pager, getLists, resetPage, resetParams } = usePaging({
		fetchFun: groupUser,
		params: queryParams
	})
	//添加成员弹窗
	const onAdd = () => {
		checkDemand.value.add(route.query.id);
	}
	// 删除成员
	const onDel = async (row:any) => {
		console.log(row)
		try{
			await feedback.confirm('是否确认删除')
			await delUser({
				group_id: route.query.id,
				user_id: row.user_id,
				user_type: row.user_type
			})
			getLists()
		}catch(error){
			console.log(error)
		}
		
	}
	//保存信息
	const handleSave = async () => {
		console.log(huaData)
		if (choose_type.value == 0) {
			await formRef.value?.validate();
			let params = JSON.parse(JSON.stringify(formData));
			console.log(params)
			await saveGroup(params)
			router.back()
		}
		if(choose_type.value == 1) {
			await orderRef.value?.validate();
			let params = JSON.parse(JSON.stringify(orderData));
			console.log(params)
			await createCooperationGroup(params)
			router.back()
		}
		if (choose_type.value == 5) {
			await huaRef.value?.validate();
			// 判断开始和结束时间
			if (huaData.start_time > huaData.end_time) {
				feedback.msgError('开始时间不能大于结束时间')
				return false;
			}
			let params = JSON.parse(JSON.stringify({...huaData, group_type: 5}));
			console.log(params)
			await saveGroup(params)
			router.back()
		}
	}

	route.query.id && getDetails();
	route.query.id && getLists();
</script>
<style scoped lang="scss">
	.btnR{
		position: absolute;
		right: 50px;
		top: 30px;
	}
	::v-deep .el-input__wrapper{
		width: 320px;
	}
</style>